import { Vue } from "./install";
import ModuleCollection from "./module/module-colliection";
import { forEachValue } from "./utils";


function installModule(store,path,module){ // module=》 _raw _children state
  // 将循环的方法放到类中来维护 
  // forEachValue(module._raw.mutations,(mutationKey,mutationValue)=>{})
  module.forEachMutation((mutationKey,mutationValue)=>{
    store.mutations[mutationKey] = ( store.mutations[mutationKey] || [])
    store.mutations[mutationKey].push((payload)=>{
      mutationValue(module.state,payload)
    })
  });
  module.forEachAction((actionKey,actionValue)=>{
    store.actions[actionKey] = ( store.actions[actionKey] || [])
    store.actions[actionKey].push((payload)=>{
      actionValue(store,payload)
    })
  });
  // forEachValue(module._children,()=>{})
  module.forEachChildren((childName,childValue)=>{
    installModule(store,path.concat(childName),childValue)
  })
}
class Store {
  // Vuex核心
  constructor(options) {
    // 将用户传递的选项进行格式化操作，格式化成一个我容易理解的数据结构
    const modules = new ModuleCollection(options);
    this.actions = {}; // 存放所有模块的action
    this.mutations = {}; // 存放所有模块的mutation
    // 将子的状态定义在父的状态上
    this.getters = {}; // 所有的计算属性
    installModule(this,[],modules.root);
    console.log(this.mutations,this.actions)
  }
  dispatch = (actionKey, payload) => {};
  commit = (mutationKey, payload) => {};
  get state() {}
}

// class Store {
//   // Vuex核心
//   constructor(options) {
//     const state = options.state;
//     // 获取用户传入的getters
//     const getters = options.getters;
//     this.getters = {};
//     const computed = {};
//     forEachValue(getters, (getterKey, getterValue) => {
//       computed[getterKey] = () => {
//         return getterValue.call(this, this.state);
//       };
//       Object.defineProperty(this.getters, getterKey, {
//         get: () => this.vm[getterKey] // 每次取值调用此方法，这个方法会去计算属性中取值，计算属性计算的值没有变化，就采用以前的，不会重新执行
//       });
//     });
//     this.vm = new Vue({
//       data: {
//         //如果这样做那用的时候
//         $$state: state,
//       },
//       computed,
//     });
//     const mutations  = options.mutations
//     this.mutations = {};
//     forEachValue(mutations,(mutationKey,mutationValue)=>{
//       this.mutations[mutationKey] = (palyoad)=> mutationValue(this.state,palyoad)
//     })

//     const actions  = options.actions
//     this.actions = {};
//     forEachValue(actions,(actionKey,actionValue)=>{
//       this.actions[actionKey] = (palyoad)=> actionValue(this,palyoad)
//     })
//   }
//   dispatch = (actionKey,payload) =>{ // const {commit} = this.$store  commit()
//     this.actions[actionKey](payload)
//   }
//   commit = (mutationKey,payload) =>{ // const {commit} = this.$store  commit()
//     this.mutations[mutationKey](payload)
//   }
//   get state() {
//     return this.vm._data.$$state;
//   }
// }
export default Store;
